//
//  HMPlaceholderTextView.swift
//  Weibo
//
//  Created by 米易雅克 on 16/4/27.
//  Copyright © 2016年 米易雅克. All rights reserved.
//

import UIKit

class HMPlaceholderTextView: UITextView {

    //占位文本
    var placeholder: String? {
        didSet {
            //别人设置什么文本，就将这个文本设置给placeholderLabel
            placeholderLabel.text = placeholder
        }
    }
    //当别人给textView的text赋值后，如果有文字，占位文本需要隐藏
    override var text: String! {
    
        didSet {
            placeholderLabel.hidden = self.hasText()
        }
    }
    /// 覆盖父类的属性，1添加override2.实现didset
    override var font: UIFont? {
        didSet {
            placeholderLabel.font = font
        }
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        prepareUi()
        //监听文字的改变，使用代理不好，外面别人也可能也适用代理 ，就会将我们自己设置的代理替换  1对1
        //通知1对多
        //注册通知
        //observer :谁来监听
        //selector: 监听的方法
        //name: 通知的名称
        //object:通知的发送者，nil ：任何人发送的通知都能接收，object指定对象，只有指定的对象发送的通知才能接收到
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("didChangeText"), name: UITextViewTextDidChangeNotification, object: self)
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    @objc private func didChangeText() {
    
        //判断有没有文字
        placeholderLabel.hidden = hasText()
    }
    
    
    private func prepareUi() {
        //添加控件
        self.addSubview(placeholderLabel)
        //添加约束，减少依赖
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
       addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 5))
       addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
        
    }
//MARK:懒加载
    //占位label
    private lazy var placeholderLabel: UILabel = {
        let label = UILabel()
        label.font = self.font
        label.textColor = UIColor.lightGrayColor()
        
        label.text = "分享新鲜事"
        label.sizeToFit()
        return label
    } ()
   
}
